package com.iisigroup.project.statistics;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.collections.MapUtils; 
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.robert.study.utils.POIUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iisigroup.log.statistics.internal.Convert20150109;
import com.iisigroup.project.statistics.model.Func4Moi;
import com.iisigroup.project.statistics.model.Function;

public class ScanBase {
    /** The Constant logger. */
    private static final Logger LOGGER = LoggerFactory.getLogger(ScanBase.class);
    /**
     * 根據class type 取得  byte []
     * */
    public Set<String> getClassByteByClassType(final Class<? extends Object> unitClass ) throws IOException{
        final String canonicalName = unitClass.getCanonicalName();
        final String classPath = StringUtils.replace(canonicalName, ".", File.separator) + ".class";                     
        final ClassLoader loader =  unitClass.getClassLoader();
        
        final InputStream is = loader.getResourceAsStream(classPath);
        final  Set<String> importedClasses = DependencyEmitter.extractImportedClasses(is, canonicalName);
        return importedClasses;
    }
    public  Map<String, String> geChtNameMap(final String properties) {
        Properties props = new Properties();
        try {
            props.load(Scan002.class.getResourceAsStream(properties));
        } catch (Exception e) {
            e.printStackTrace();
        }
        final Set<Object> keys = props.keySet();
        final Map<String, String> siteIdMap = new HashMap<String, String>();
        for (Object key : keys) {
            Object value = props.get(key);
            siteIdMap.put(key.toString(), value.toString());
        }
        return siteIdMap;
  }
    public static void outputFile(final File file, String data) throws IOException {
        BufferedWriter bWriter = null;
        try {
            bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
            bWriter.write(data);
        } finally {
            if (bWriter != null) {
                try {
                    bWriter.close();
                } catch (IOException e) {
                     LOGGER.error(e.getMessage() ,e );
                }
            }
        }
    }
    public static void postAction(final Map<String, Function> data){
        if(MapUtils.isNotEmpty(data)){
            final Collection<Function> functions = data.values();
            for(Function function : functions){
                Func4Moi outputRaw = Convert20150109.convertData(function);
                
                System.out.println(ToStringBuilder.reflectionToString(outputRaw));
            }
         }
    }
    public static void exportReport(final Map<String, Function> data, final String fileName) throws ParsePropertyException, InvalidFormatException, IOException {
        final List<String> codeTAskList = new ArrayList<String>( data.keySet());
        Collections.sort(codeTAskList);
        for(String name : codeTAskList){
            Function value = data.get(name);
//          sbf.append(value.getFunctionChtName()+"/"+ name + "---------------").append("\r");      
           
//          sbf.append("Controller Name: "+StringUtils.join(value.getControllerNames(), ",") ).append("\r");     
//          sbf.append("Controller 所使用的程式/元件,AE元件名稱: "+ value.displayControllerUsedCompoenent()).append("\r");   
//          sbf.append("Service Name: "+StringUtils.join(value.getServiceNames(), ",") ).append("\r");   
//          sbf.append("Service 所使用的程式/元件,AE元件名稱: "+value.displayServiceUsedCompoenent()).append("\r");  
        }
        Map<String, Object> beans = new HashMap<String, Object>();
        beans.put("title", "This is test function");
        beans.put("codeTAskList", codeTAskList);
        beans.put("data", data);
        XLSTransformer transformer = new XLSTransformer();

        final Workbook aHSSFWorkbook = transformer.transformXLS(ScanBase.class.getResource("template.xls").openStream(), beans);
        POIUtils.writeWorkbookOut(new File(fileName), aHSSFWorkbook);
        LOGGER.info("final condition..........");
        postAction(data);
    }
}
